// pages/SearchModule/homePage.js
const app = getApp()
Page({
    data: {
        postNum: 10,//每页帖文个数
        /*在获取list和刷新list中使用*/
        //实现下拉到底后滚动条位置刷新
        scrollTop: 0,
        nowScrollTop: 0,
        isTriggered: false,//配合scroll-view刷新
        postList: {},
        /*
        postId
        barId
        barName
        postType    该贴文类型（0-普通，1-热门，2-加精，3-置顶）
        postTitle
        postText
        creatorId
        creatorName
        createTime
        lastEditTime
        popularity
        viewSum
        likeSum
        collectSum
        dislikeSum
        commentSum
        hasLike
        hasDislike
        hasCollect
        creatorAvatar   >发帖人头像
        */
        currentPage: 1,
        pageSize: 10,//每一页的帖子数量
    },
    tapToPage: null,
    loadToPage: null,
    returnToPage: false,//返回此页面的时候也能tarbar更新，待实现
    onShow: function(){
        if(this.loadToPage){
            this.loadToPage = false
            this.tapToPage = false
            return
        }
        this.tapToPage = true
    },
    onTabItemTap: function(item) {
        if (this.tapToPage){
            this.tapToPage = false
            return;
        }
        console.log("触发tarbar栏刷新")
        this.refreshPostList()
    },
    onLoad: function (options) {
        this.loadToPage = true
        this.initPostList()
    },

    initPostList(){
        //获取帖子列表
        var that = this
        wx.request({
            url: `http://${app.globalData.target}//post/recommend`,
            data: {
                currentPage: that.data.currentPage,
                pageSize: that.data.pageSize
            },
            header: {
                "hello-token": wx.getStorageSync("hello-token")
            },
            method: 'GET',
            success: function(res){
                console.log('getPostList Result:')
                console.log(res)
                that.setData({
                    postList: res.data.result.postList
                })
                var _postList = that.data.postList
                for(var i=0; i<_postList.length; i++){
                    that.getUserDetail(i)
                }
            },
            fail: function(e) {
                console.log('fail to get postList')
                console.log(e)
            }
        })
    },
    getUserDetail(i){
        var that = this
        var userId = that.data.postList[i].creatorId
        wx.request({
            url: `http://${app.globalData.target}//user/displayedInfo`,
            data: {
                userId: userId
            },
            header: {
                "hello-token": wx.getStorageSync("hello-token")
            },
            method: 'GET',
            success: function(res){
                that.setData({
                    [`postList[${i}].creatorName`]: res.data.result.userName,
                    [`postList[${i}].creatorAvatar`]: res.data.result.avatarPath
                })
            },
            fail: function(e){
                console.log(e)
            }
        })
    },

    refreshPostList(){
        //刷新帖子列表
        var that = this
        that.setData({
            postList: {},
        })
        wx.request({
            url: `http://${app.globalData.target}//post/getHotPosts`,
            data: {
                postAmount: that.data.postNum
            },
            header: {
                "hello-token": wx.getStorageSync("hello-token")
            },
            method: 'GET',
            success: function(res){
                console.log('refreshPostList Result:')
                console.log(res)
                that.setData({
                    postList: res.data.result,
                    isTriggered: false,
                    scrollTop: 0,
                    currentPage: 1
                })
                var _postList = that.data.postList
                for(var i=0; i<_postList.length; i++){
                    that.getUserDetail(i)
                }
            },
            fail: function(e) {
                console.log('fail to refresh postList')
                console.log(e)
            }
        })
    },

    goToPostPage: function(e){
        var that = this
        var postid = e.currentTarget.dataset.postid
        //跳转到相应的帖子页面
        wx.navigateTo({
            url: `../PostsModule/generalPost?postid=${postid}`
        })
    },
    scrollBinder: function(e){
        var that = this
        that.setData({
            nowScrollTop: e.detail.scrollTop
        })
    },
    handleRefresher: function(){
        console.log("触发下拉刷新")
        this.refreshPostList()
    },
    handleToLower: function(){
        console.log("触发上拉加载更多")
        var that = this
        wx.showLoading({
            title: '正在加载',
        })
        //测试用，模拟“加载更多”接口返回数据，实现中要判断是否还有更多
        var postList = that.data.postList
        var newScrollTop = that.data.nowScrollTop + 40
        var newPage = that.data.currentPage + 1
        //请求下一页列表数据
        wx.request({
            url: `http://${app.globalData.target}//post/recommend`,
            data: {
                currentPage: newPage,
                pageSize: that.data.pageSize
            },
            header: {
                "hello-token": wx.getStorageSync("hello-token")
            },
            method: 'GET',
            success: function(res){
                console.log(res)
                var nextList = res.data.result.postList
                //判断是否为空
                console.log(nextList.length)
                if(nextList.length != 0){
                    that.setData({
                        postList: postList.concat(nextList),
                        scrollTop: newScrollTop,
                        currentPage: newPage
                    })
                    var _postList = that.data.postList
                    for(var i=0; i<_postList.length; i++){
                        that.getUserDetail(i)
                    }
                }
            },
            fail: function(e) {
                console.log('fail to get postList')
                console.log(e)
            }
        })
        wx.hideLoading()
    }
})